import { _decorator, Button, Component, instantiate, Node, tween, Vec3 } from 'cc';
import { Enemy } from './Enemy';
import { Constants, EnemyType } from '../game/Constants';
import { MovePath } from './MovePath';
import { UIGame } from '../gui/UIGame';
const { ccclass, property } = _decorator;

@ccclass('EnemyManger')
export class EnemyManger extends Component {
    public static Instance: EnemyManger = null;
    @property([MovePath]) movePathList: MovePath[] = [];
    @property(Node) Minion_1: Node = null!;
    @property(Node) Minion_2: Node = null!;
    @property(Node) Boss: Node = null!;
    private enemyList: Enemy[] = [];

    onLoad(): void {
        EnemyManger.Instance = this;
    }

    start() {
        UIGame.Instance.BossBar.progress = 0;
    }

    // 生成规则 初级 0-9s内  中级 10-19s 高级 20-29s, 30s生成大Boss
    public autoCreateEnemy(level: number = 1) {
        if (level === 1) {
            this.createEnemyList(10, 1, EnemyType.MINION_2, level);
            this.createEnemyList(10, 1, EnemyType.MINION_2, level);
            UIGame.Instance.BossBar.progress = 0;
            tween(UIGame.Instance.BossBar).to(12, { progress: 0.34 }).start();
        }

        if (level === 2) {
            this.createEnemyList(10, 1, EnemyType.MINION_1, level);
            this.createEnemyList(10, 1, EnemyType.MINION_1, level);
            tween(UIGame.Instance.BossBar)
                .to(12, { progress: 0.65 })
                .start();
        }

        if (level === 3) {
            this.createEnemyList(10, 1, EnemyType.MINION_1, level);
            this.createEnemyList(10, 1, EnemyType.MINION_2, level);
            tween(UIGame.Instance.BossBar)
                .to(12, { progress: 1 })
                .start();
        }
    }

    /** 创建Boss */
    public createBossEnemy() {
        this.createEnemyNode(EnemyType.BOSS, 3);
    }

    /**
     * 创建敌人组
     * @param num 数量
     * @param interval 间隔
     * @param enemyType 怪物类型
     * @param enemyLevel 怪物等级
     */
    private createEnemyList(num: number, interval: number, enemyType: EnemyType, enemyLevel: number) {
        let count = 0;
        const createNext = () => {
            this.createEnemyNode(enemyType, enemyLevel);
            count++;
            if (count >= num) {
                return;
            }
            // 随机间隔：基础interval±0.5s
            const randInterval = interval + (Math.random() - 0.5);
            setTimeout(createNext, Math.max(0.1, randInterval) * 1000);
        };
        createNext();
    }

    /**
     * 创建单个敌人
     * @param enemyType 怪物类型
     * @param enemyLevel 怪物等级
     * @returns 
     */
    private createEnemyNode(enemyType: EnemyType, enemyLevel: number) {
        let enemyNode: Node | null = null;
        switch (enemyType) {
            case EnemyType.MINION_1:
                enemyNode = instantiate(this.Minion_1);
                break;
            case EnemyType.MINION_2:
                enemyNode = instantiate(this.Minion_2);
                break;
            case EnemyType.BOSS:
                enemyNode = instantiate(this.Boss);
                break;
        }

        if (enemyNode) {
            const path = this.getRandomPath();
            if (!path) {
                console.warn("没有可用的移动路径");
                return;
            }
            const targetPos = path.beginNode.position.clone();
            enemyNode.active = true;
            enemyNode.parent = path.node;
            enemyNode.setPosition(targetPos);
            enemyNode.setWorldRotationFromEuler(0, 0, 0);
            const enemy = enemyNode.getComponent(Enemy);
            if (enemy) {
                enemy.level = enemyLevel;
                enemy.moveToAttackPos(path.endNode.position.clone());
                enemy.onEnemyDid = this.onEnemyDid.bind(this);
                this.enemyList.push(enemy);
            }
        }
    }

    /**
     * 检测是否有敌人进入攻击范围
     * @param pos 要塞最大攻击坐标,敌人从右侧进入，小于此坐标即进入攻击范围
     * @returns 
     */
    public getEnemyInRange(pos: Vec3): Enemy | null {
        for (const enemy of this.enemyList) {
            if (enemy && !enemy.isDead && enemy.node.getWorldPosition().x < pos.x) {
                return enemy;
            }
        }
        return null;
    }

    /** 群伤攻击 */
    public doAreaDamage(damage: number) {
        this.enemyList.forEach(enemy => {
            if (enemy && !enemy.isDead) {
                enemy.onAttack(damage);
            }
        });
    }


    /** 获取随机移动路径 */
    private getRandomPath(): MovePath {
        const randomIndex = Math.floor(Math.random() * this.movePathList.length);
        return this.movePathList[randomIndex];
    }

    private onEnemyDid(enemy: Enemy) {
        // 这里可以添加敌人死亡后的特效或奖励逻辑
        const index = this.enemyList.indexOf(enemy);
        if (index !== -1) {
            this.enemyList.splice(index, 1);
        }
    }

    private removeEnemy() {
        this.enemyList.forEach(enemy => {
            enemy.killEnemy();
        });
    }
}